package br.com.webservicedelivery.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.webservicedelivery.domain.ItensPedido;
import br.com.webservicedelivery.util.HibernateUtil;

public class ItensPedidoDAO {
	public void salvar(ItensPedido itens) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;

		try {
			transacao = sessao.beginTransaction();
			sessao.save(itens);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;
		} finally {
			sessao.close();

		}

	}

	@SuppressWarnings("unchecked")
	public List<ItensPedido> listar() {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		List<ItensPedido> itens = null;

		try {
			Query consulta = sessao.getNamedQuery("ItensPedido.listar");
			itens = consulta.list();

		} catch (RuntimeException ex) {
			throw ex;
		} finally {
			sessao.close();
		}

		return itens;

	}

	public ItensPedido buscarPorId(Long id) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		ItensPedido itens = null;

		try {
			Query consulta = sessao.getNamedQuery("ItensPedido.buscarPorId");
			consulta.setLong("id", id);

			itens = (ItensPedido) consulta.uniqueResult();

		} catch (RuntimeException ex) {
			throw ex;
		} finally {
			sessao.close();

		}
		return itens;

	}

	public void excluir(ItensPedido itens) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;

		try {
			transacao = sessao.beginTransaction();
			sessao.delete(itens);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;
		} finally {
			sessao.close();

		}
	}

	public void editar(ItensPedido itens) {
		Session sessao = HibernateUtil.getSessionFactory().openSession();
		Transaction transacao = null;

		try {
			transacao = sessao.beginTransaction();
			sessao.update(itens);
			transacao.commit();

		} catch (RuntimeException ex) {
			if (transacao != null) {
				transacao.rollback();
			}
			throw ex;
		} finally {
			sessao.close();

		}

	}
}
